﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsJobHistoryTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// Job History Business Object
    /// </summary>

    public class JobHistory : BOBase
    {
        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected JobHistory() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        
        /// <summary>
        /// JobID.
        /// </summary>
        public string JobID
        {
            get { return _jobID; }
            set
            {
                if (_jobID != value)
                {
                    if (OnPropertyChanging("JobID", _jobID, value))
                    {
                        string oldValue = _jobID;
                        _jobID = value;
                        OnPropertyChanged("JobID", oldValue, value);
                    }
                }
            }
        }  private string _jobID = null;


        /// <summary>
        /// ActionPerformed.
        /// </summary>
        public string ActionPerformed
        {
            get { return _actionPerformed; }
            set
            {
                if (_actionPerformed != value)
                {
                    if (OnPropertyChanging("ActionPerformed", _actionPerformed, value))
                    {
                        string oldValue = _actionPerformed;
                        _actionPerformed = value;
                        OnPropertyChanged("ActionPerformed", oldValue, value);
                    }
                }
            }
        }  private string _actionPerformed = null;


        /// <summary>
        /// Date/time at which the JobHistory was created.
        /// </summary>
        public DateTime? ActionDate
        {
            get { return _actionDate; }
            set
            {
                if (_actionDate != value)
                {
                    if (OnPropertyChanging("ActionDate", _actionDate, value))
                    {
                        DateTime? oldValue = _actionDate;
                        _actionDate = value;
                        OnPropertyChanged("ActionDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _actionDate = null;

        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty JobHistory object.
        /// </summary>
        public static JobHistory CreateNew()
        {
            JobHistory obj = new JobHistory();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.ActionDate = DateTime.Now;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static JobHistory CreateNew(JobHistoryCollection collection)
        {
            JobHistory obj = CreateNew();

            // Get next/unique ID for the new object.
            //int minVal = 0;
            //foreach (JobHistory JobHistory in collection)
            //{
            //    if (JobHistory.JobHistoryID < minVal)
            //        minVal = JobHistory.JobHistoryID;
            //}
            //obj.JobHistoryID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetCompleteJobHistory

        /// <summary>
        /// Returns a collection of JobHistory.
        /// </summary>
        public static JobHistoryCollection GetCompleteJobHistory(string jobid)
        {
            Job_HistoriesTableAdapter adapter = new Job_HistoriesTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsJobHistory.Job_HistoriesDataTable tbl = adapter.GetData(jobid);

            JobHistoryCollection list = new JobHistoryCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsJobHistory.Job_HistoriesRow row in tbl.Rows)
                {
                    JobHistory jobhistory = new JobHistory();
                    RelationalToObject(jobhistory, row);
                    list.Add(jobhistory);
                }
            }

            return (list);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified JobHistory.
        /// </summary>
        public static void Update(JobHistory obj)
        {
            bool updateJobHistory = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateJobHistory = (obj.ObjState != ObjectState.Unchanged);

                if (!updateJobHistory)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsJobHistory.Job_HistoriesDataTable tbl = null;
            if (updateJobHistory)
            {
                Job_HistoriesTableAdapter adapter = new Job_HistoriesTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();


                tbl = new dsJobHistory.Job_HistoriesDataTable();
                dsJobHistory.Job_HistoriesRow row = tbl.NewJob_HistoriesRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("JobHistoryID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {
                                
            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("JobHistory: JobID={0}, ActionPerformed={1}, {2}", JobID, ActionPerformed));
        }

        #endregion

        #endregion

        #region Privates


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more SubAdmin objects.
    /// </summary>

    public class JobHistoryCollection : List<JobHistory>
    {
        #region Types

        public class UserComparer : IComparer<JobHistory>
        {
            public int Compare(JobHistory jh1, JobHistory jh2)
            {
                return (String.Compare(jh1.JobID, jh2.JobID));
            }
        }

        #endregion

        #region Public Methods

        #region FindByJobID

        public JobHistory FindByJobID(string JobID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].JobID == JobID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion

    }
}
